package com.atguigu.lease.web.app.intercepter;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.context.LocalContext;
import com.atguigu.lease.web.app.service.UserInfoService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.login.LoginContext;

@Component
public class AppLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("Access_token");
        if (jwt == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }

        Long userId = JwtUtil.parseToken(jwt);
        if (userId == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        //判断数据库中是否存在该用户
        UserInfo userInfo = userInfoService.getById(userId);
        if (userInfo == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }

        //将用户存储到ThreadLocal中
        LocalContext.setUserInfo(userInfo);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LocalContext.remove();
    }
}
